/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <string.h>
#include <android/bitmap.h>
#include <android/log.h>
#include <jni.h>

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
 */

#define  LOG_TAG    "Native"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)


extern "C" {

JNIEXPORT jstring JNICALL
        Java_example_charlyzhang_com_jnicalljava_MainActivity_stringFromJNI(JNIEnv *env, jobject thiz);

JNIEXPORT jobject JNICALL
        Java_example_charlyzhang_com_jnicalljava_MainActivity_getImage(JNIEnv *env, jclass type,  jstring path);
}

JNIEXPORT jstring JNICALL
        Java_example_charlyzhang_com_jnicalljava_MainActivity_stringFromJNI(JNIEnv *env, jobject thiz)
{
    jstring rtn;
    rtn = env->NewStringUTF("Hello from JNI !");
    return rtn;
}

JNIEXPORT jobject JNICALL Java_example_charlyzhang_com_jnicalljava_MainActivity_getImage(JNIEnv *env, jclass type, jstring path)
{
    jclass cls = env->FindClass("example/charlyzhang/com/jnicalljava/BitmapService");
    jmethodID mid = env->GetStaticMethodID(cls, "getImageFromSD", "(Ljava/lang/String;)Landroid/graphics/Bitmap;");
    jobject bitmap = env->CallStaticObjectMethod(cls,mid,path);

    void *addr;
    AndroidBitmapInfo info;
    int errorCode;

    if ((errorCode = AndroidBitmap_lockPixels(env, bitmap, &addr)) != 0) {
        LOGI("error %d", errorCode);
    }

    if ((errorCode = AndroidBitmap_getInfo(env, bitmap, &info)) != 0) {
        LOGI("error %d", errorCode);
    }

    LOGI("bitmap info: %d wide, %d tall, %d ints per pixel", info.width, info.height, info.format);


    long size = info.width * info.height * info.format;
    int *pixels = new int[size];
    memcpy(pixels, addr, size * sizeof(int));

    if ((errorCode = AndroidBitmap_unlockPixels(env, bitmap)) != 0) {
        LOGI("error %d", errorCode);
    }

    delete [] pixels;

    return bitmap;
}